/**
jquery extend
**/
$.extend({ 
/** 
 1. 设置cookie的值，把name变量的值设为value   
example $.cookie(’name’, ‘value’);
 2.新建一个cookie 包括有效期 路径 域名等
example $.cookie(’name’, ‘value’, {expires: 7, path: ‘/’, domain: ‘jquery.com’, secure: true});
3.新建cookie
example $.cookie(’name’, ‘value’);
4.删除一个cookie
example $.cookie(’name’, null);
5.取一个cookie(name)值给myvar
var account= $.cookie('name');
**/
    cookieHelper: function(name, value, options) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            var path = options.path ? '; path=' + options.path : '';
            var domain = options.domain ? '; domain=' + options.domain : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    },
	ImgReSize1: function(obj, maxW, maxH, view_type){
		var _w = $(obj).width(), _h = $(obj).height(), picLayout = _w / _h;
		
		
		if(view_type == 'contain'){
			if(_w <= _h){
				maxH = maxH > _h ? _h : maxH;
				$(obj).height(maxH).show();
			}else{
				maxW = maxW > _w ? _w : maxW;
				$(obj).width(maxW).show();
			}
		}else{
			if(_w >= _h){
				maxH = maxH > _h ? _h : maxH;
				$(obj).height(maxH).show();
			}else{
				maxW = maxW > _w ? _w : maxW;
				$(obj).width(maxW).show();
			}
		}
//		if($(obj).attr('id') == 'uploader-identity_1-img'){
//			alert([view_type, _w, _h, '||', maxW, maxH]);	
//		}
	},
	ImgReSize: function(obj, maxW, maxH, view_type){
		var _w = $(obj).width(), _h = $(obj).height(), picLayout = _w / _h;
		var targ_w , targ_h;
		var diff_w = _w - maxW, diff_h = _h - maxH;
		//封面：充满画布；内容：显示全部
		view_type = (typeof view_type == 'undefined') ? 'contain' : view_type;
		if(diff_w > 0 || diff_h > 0){
			//显示全部内容
			if(view_type == 'contain'){
				if(diff_w > diff_h){
					targ_w = maxW;
					targ_h = Math.round(maxW / picLayout);
				}else{
					targ_h = maxH;
					targ_w = Math.round(maxH * picLayout);
				}
			}else{
				//封面显示局部
				if(diff_w < diff_h){
					targ_w = maxW;
					targ_h = Math.round(maxW / picLayout);
				}else{
					targ_h = maxH;
					targ_w = Math.round(maxH * picLayout);
				}
			}
		}else{
			targ_w = _w;
			targ_h = _h;
		}
		$(obj).width(targ_w).height(targ_h).show();
	},
	ImgContain: function(obj, maxW, maxH){
		$.ImgReSize(obj, maxW, maxH, 'contain');
	},
	ImgCover: function(obj, maxW, maxH){
		$.ImgReSize(obj, maxW, maxH, 'cover');
	}
}); 
function resetSize(srcW, srcH, maxW, maxH, view_type){
	var _w = srcW, _h = srcH, picLayout = _w / _h;
	var targ_w , targ_h;
	var diff_w = _w - maxW, diff_h = _h - maxH;
	//封面：充满画布；内容：显示全部
	view_type = (typeof view_type == 'undefined') ? 'contain' : view_type;
	if(diff_w > 0 || diff_h > 0){
		//显示全部内容
		if(view_type == 'contain'){
			if(diff_w > diff_h){
				targ_w = maxW;
				targ_h = Math.round(maxW / picLayout);
			}else{
				targ_h = maxH;
				targ_w = Math.round(maxH * picLayout);
			}
		}else{
			//封面显示局部
			if(diff_w < diff_h){
				targ_w = maxW;
				targ_h = Math.round(maxW / picLayout);
			}else{
				targ_h = maxH;
				targ_w = Math.round(maxH * picLayout);
			}
		}
	}else{
		targ_w = _w;
		targ_h = _h;
	}
	return [targ_w, targ_h];
}


var wrapStr = '\n';//'<br>';//'\n';
var blankStr = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';//'   ';
var JSONFormat = (function(){
    var _toString = Object.prototype.toString;
 
    function format(object, indent_count){
        var html_fragment = '';
        switch(_typeof(object)){
            case 'Null' :0
                html_fragment = _format_null(object);
                break;
            case 'Boolean' :
                html_fragment = _format_boolean(object);
                break;
            case 'Number' :
                html_fragment = _format_number(object);
                break;
            case 'String' :
                html_fragment = _format_string(object);
                break;
            case 'Array' :
                html_fragment = _format_array(object, indent_count);
                break;
            case 'Object' :
                html_fragment = _format_object(object, indent_count);
                break;
        }
        return html_fragment;
    };
 
    function _format_null(object){
        return '<span class="json_null">null</span>';
    }
 
    function _format_boolean(object){
        return '<span class="json_boolean">' + object + '</span>';
    }
 
    function _format_number(object){
        return '<span class="json_number">' + object + '</span>';
    }
 
    function _format_string(object){
        if(0 <= object.search(/^http/)){
            object = '<a href="' + object + '" target="_blank" class="json_link">' + object + '</a>'
        }
        return '<span class="json_string">"' + object + '"</span>';
    }
 
    function _format_array(object, indent_count){
        var tmp_array = [];
        for(var i = 0, size = object.length; i < size; ++i){
            tmp_array.push(indent_tab(indent_count) + format(object[i], indent_count + 1));
        }
        return '[' + wrapStr
            + tmp_array.join(',' + wrapStr)
            + wrapStr + indent_tab(indent_count - 1) + ']';
    }
 
    function _format_object(object, indent_count){
        var tmp_array = [];
        for(var key in object){
            tmp_array.push( indent_tab(indent_count) + '<span class="json_key">"' + key + '"</span>:' +  format(object[key], indent_count + 1));
        }
        return '{' + wrapStr
            + tmp_array.join(',' + wrapStr)
            + wrapStr + indent_tab(indent_count - 1) + '}';
    }
 
    function indent_tab(indent_count){
        return (new Array(indent_count + 1)).join(blankStr);
    }
 
    function _typeof(object){
        var tf = typeof object,
            ts = _toString.call(object);
        return null === object ? 'Null' :
            'undefined' == tf ? 'Undefined'   :
                'boolean' == tf ? 'Boolean'   :
                    'number' == tf ? 'Number'   :
                        'string' == tf ? 'String'   :
                            '[object Function]' == ts ? 'Function' :
                                '[object Array]' == ts ? 'Array' :
                                    '[object Date]' == ts ? 'Date' : 'Object';
    };
 
    function loadCssString(){
        var style = document.createElement('style');
        style.type = 'text/css';
        var code = Array.prototype.slice.apply(arguments).join('');
        try{
            style.appendChild(document.createTextNode(code));
        }catch(ex){
            style.styleSheet.cssText = code;
        }
        document.getElementsByTagName('head')[0].appendChild(style);
    }
 
    loadCssString(
        '.json_key{ color: purple;}',
        '.json_null{color: red;}',
        '.json_string{ color: #077;}',
        '.json_link{ color: #717171;}',
        '.json_array_brackets{}');
 
    var _JSONFormat = function(origin_data){
        this.data = 'string' != typeof origin_data ? origin_data :
            JSON && JSON.parse ? JSON.parse(origin_data) : eval('(' + origin_data + ')');
    };
 
    _JSONFormat.prototype = {
        constructor : JSONFormat,
        toString : function(){
            return format(this.data, 1);
        }
    }
 
    return _JSONFormat;
 
})();
 
function create_result_contatiner(){
    var $result = $('<pre id="result" style=" width: 100%; height: 100%; overflow: scroll; overflow-x: scroll; overflow-y:scroll"></pre>')
    var $result_container = $('<div id="result_container" style="position: fixed; top: 1%; right: 8px; width: 5%; height: 97%; margin: 0; padding: 0;  border:1px solid skyblue; background: #f8f8f8; line-height: 1.2em; font-size: 14px; cursor: pointer;"></div>');
    $result_container.append($result);
    $result_container.hover(function(){
        $(this).stop(true).animate({width:'50%'}, 'slow');
    }, function(){
        $(this).stop(true).animate({width:'5%'}, 'slow');
    });
    $('body').append($result_container);
    return [$result_container, $result];
}

var Utils = new Object();

Utils.htmlEncode = function(text)
{
  return text.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

Utils.trim = function( text )
{
  if (typeof(text) == "string")
  {
    return text.replace(/^\s*|\s*$/g, "");
  }
  else
  {
    return text;
  }
}

Utils.isEmpty = function( val )
{
  switch (typeof(val))
  {
    case 'string':
      return Utils.trim(val).length == 0 ? true : false;
      break;
    case 'number':
      return val == 0;
      break;
    case 'object':
      return val == null;
      break;
    case 'array':
      return val.length == 0;
      break;
    default:
      return true;
  }
}

Utils.isNumber = function(val)
{
  var reg = /^[\d|\.|,]+$/;
  return reg.test(val);
}
Utils.isMobile = function(val)
{
  var reg = /^[1][3,5,8][0-9]{9}$/; 
  return reg.test(val);
}

Utils.isInt = function(val)
{
  if (val == "")
  {
    return false;
  }
  var reg = /\D+/;
  return !reg.test(val);
}

Utils.isEmail = function( email )
{
  var reg1 = /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/;

  return reg1.test( email );
}

Utils.isTel = function ( tel )
{
  var reg = /^[\d|\-|\s|\_]+$/; //只允许使用数字-空格等

  return reg.test( tel );
}

Utils.fixEvent = function(e)
{
  var evt = (typeof e == "undefined") ? window.event : e;
  return evt;
}

Utils.srcElement = function(e)
{
  if (typeof e == "undefined") e = window.event;
  var src = document.all ? e.srcElement : e.target;

  return src;
}

Utils.isTime = function(val)
{
  var reg = /^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}$/;

  return reg.test(val);
}

document.getCookie = function(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++) {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0])
      return decodeURIComponent(aCrumb[1]);
  }

  // a cookie with the requested name does not exist
  return null;
}

document.setCookie = function(sName, sValue, sExpires)
{
  var sCookie = sName + "=" + encodeURIComponent(sValue);
  if (sExpires != null){
    sCookie += "; expires=" + sExpires;
  }

  document.cookie = sCookie;
}

document.removeCookie = function(sName,sValue)
{
  document.cookie = sName + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}

function getPosition(o)
{
    var t = o.offsetTop;
    var l = o.offsetLeft;
    while(o = o.offsetParent)
    {
        t += o.offsetTop;
        l += o.offsetLeft;
    }
    var pos = {top:t,left:l};
    return pos;
}

function cleanWhitespace(element)
{
  var element = element;
  for (var i = 0; i < element.childNodes.length; i++) {
   var node = element.childNodes[i];
   if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
     element.removeChild(node);
   }
}

function obj2str(o){
   var r = [];
   if(typeof o == "string" || o == null) {
     return o;
   }
   if(typeof o == "object"){
     if(!o.sort){
       r[0]="{"
       for(var i in o){
         r[r.length]=i;
         r[r.length]=":";
         r[r.length]=obj2str(o[i]);
         r[r.length]=",";
       }
       r[r.length-1]="}"
     }else{
       r[0]="["
       for(var i =0;i<o.length;i++){
         r[r.length]=obj2str(o[i]);
         r[r.length]=",";
       }
       r[r.length-1]="]"
     }
     return r.join("");
   }
   return o.toString();
}